﻿using System;
using System.Collections.Generic; 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using System.Data;
using Runda.CMS.Common.Utility;

namespace Runda.CMS.Portal.Budget
{
    public partial class RptSalesBudgetByCustomer2 : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "AgencyName";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                for (int i = 2012; i <= 2015; i++)
                {
                    ddlBudgetYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "DepartmentCode";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", "0"));
                ddlCompany.SelectedValue = "0";

                dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString());
                ddlDept.DataSource = dt;
                ddlDept.DataTextField = "Departmentname";
                ddlDept.DataValueField = "Departmentname";
                ddlDept.DataBind();
                ddlDept.Items.Add(new ListItem("--不限--", "0"));
                ddlDept.SelectedValue = "0";

                BindGrid(1);
                Calculate();
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            //if (e.CommandName.ToLower() == "delete")
            //{
            //    BudgetBll bll = new BudgetBll();
            //    bll.DeleteByBudgetID(new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["BudgetID"].ToString()));
            //}
            //BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BudgetBll().QueryCustomer2SalesBudget_Rpt(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            
            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcCustomerSalesBudget_Rpt(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                hfsumcustomernumber.Value = string.Format("{0:N}", dt.Rows[0]["customerNumber"]);
                hfsum1Amount.Value = string.Format("{0:N}", dt.Rows[0]["m01Amount"]);
                hfsum2Amount.Value = string.Format("{0:N}", dt.Rows[0]["m02Amount"]);
                hfsum3Amount.Value = string.Format("{0:N}", dt.Rows[0]["m03Amount"]);

                hfsum4Amount.Value = string.Format("{0:N}", dt.Rows[0]["m04Amount"]);
                hfsum5Amount.Value = string.Format("{0:N}", dt.Rows[0]["m05Amount"]);
                hfsum6Amount.Value = string.Format("{0:N}", dt.Rows[0]["m06Amount"]);
                hfsum7Amount.Value = string.Format("{0:N}", dt.Rows[0]["m07Amount"]);

                hfsum8Amount.Value = string.Format("{0:N}", dt.Rows[0]["m08Amount"]);
                hfsum9Amount.Value = string.Format("{0:N}", dt.Rows[0]["m09Amount"]);
                hfsum10Amount.Value = string.Format("{0:N}", dt.Rows[0]["m10Amount"]);
                hfsum11Amount.Value = string.Format("{0:N}", dt.Rows[0]["m11Amount"]);
                hfsum12Amount.Value = string.Format("{0:N}", dt.Rows[0]["m12Amount"]);

                hfsumTotalAmount.Value = string.Format("{0:N}", dt.Rows[0]["totalAmount"]);

            }
            else
            {
                hfsum1Amount.Value = "0";
                hfsum2Amount.Value = "0";
                hfsum3Amount.Value = "0";
                hfsum4Amount.Value = "0";

                hfsum5Amount.Value = "0";
                hfsum6Amount.Value = "0";
                hfsum7Amount.Value = "0";
                hfsum8Amount.Value = "0";

                hfsum9Amount.Value = "0";
                hfsum10Amount.Value = "0";
                hfsum11Amount.Value = "0";
                hfsum12Amount.Value = "0";

               hfsumTotalAmount.Value = "0";

            }
        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and [BudgetYear]  = '").Append(ddlBudgetYear.SelectedValue).Append("'");
            }

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and [CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            int RecordCount = 0;
            RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (base.CurrentUserEntity.UserName == "郭海涛"
            //    || base.CurrentUserEntity.UserName == "史莹"
            //    || base.CurrentUserEntity.UserName == "王静"
            //    || base.CurrentUserEntity.UserName == "顾悦"
            //    || base.CurrentUserEntity.UserName == "宋欣"
            //    || base.CurrentUserEntity.UserName == "徐雪峰"
            //    || base.CurrentUserEntity.UserName == "胡日成"
            //    || base.CurrentUserEntity.UserName == "崔丽丽"
            //    || base.CurrentUserEntity.UserName == "官俊"
            //    || base.CurrentUserEntity.UserName == "李娜"
            //    || base.CurrentUserEntity.UserName == "张佳锦"
            //    )
            //{
            //    sb.Append(" and ([company] in(").Append("select DepartmentCode from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
            //}
            //else
            //{
            //    sb.Append(" and ([sales] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            //    sb.Append(" or [sales] ='").Append(base.CurrentUserEntity.UserName).Append("'");
            //    sb.Append(" or [Producter] ='").Append(base.CurrentUserEntity.UserName).Append("'");
            //    sb.Append(" or [ProductManager] ='").Append(base.CurrentUserEntity.UserName).Append("')");
            //}


            sb.Append(" and ((company in(").Append("select DepartmentCode from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" and left(productCategoryCode,6) in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
            sb.Append(" or [sales] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            sb.Append(" or [sales] ='").Append(base.CurrentUserEntity.UserName).Append("'");
            sb.Append(" or [Producter] ='").Append(base.CurrentUserEntity.UserName).Append("')");

            if (ddlCompany.SelectedValue != "0")
            {
                sb.Append(" and company='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            if (ddlDept.SelectedValue != "0")
            { sb.Append(" and [sales] in(").Append("select username from vw_sysUser where DepartmentName ='").Append(ddlDept.SelectedValue.ToString()).Append("')"); }


            if (txtCustomerName.Text.Trim() != "")
            { 
                sb.Append(" and customerID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }
            
            if (txtCategoryName.Text.Trim() != "")
            {
                sb.Append(" and ProductCategoryID in(").Append("select  categoryGUID from Cms_Ctrt_InstrumentCategory where categoryName like '%").Append(txtCategoryName.Text.Trim()).Append("%')");
            }
            return sb.ToString();
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            Calculate();
            BindGrid(1);

        }
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BudgetBll bll = new BudgetBll();

            DataTable dt = bll.ExportCustomerSalesBudget_Rpt(Whereclause);

            Export.Export2Excel(dt, "销售预算一览表", Page.Response);

        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {

            DataTable dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString(), ddlCompany.SelectedValue.ToString());
            ddlDept.DataSource = dt;
            ddlDept.DataTextField = "Departmentname";
            ddlDept.DataValueField = "Departmentname";
            ddlDept.DataBind();
            ddlDept.Items.Add(new ListItem("--不限--", "0"));
            ddlDept.SelectedValue = "0";
        }
    }
}
